package com.sw.youvote.client.quizwizard;

import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;



import com.google.gwt.core.client.GWT;


public class FormularioUploadImagen {

	private final String URL_UPLOAD_IMAGES = "/youvote/uploadImage";
	 
	private FormPanel form = new FormPanel(); 
    private FileUpload fu =  new FileUpload();
    private Image imagen = new Image();
    
    public FormularioUploadImagen() { 
    } 
    
    private String parseString(String in) {
    	String out = null;
    	if (in !=null) {
    		int beginIndex = in.indexOf(">")+1;
    		int endIndex = in.indexOf("</");
    		out = in.substring(beginIndex, endIndex);
    	}
    	return out;
    }
    
 
    @SuppressWarnings("deprecation") 
    public Widget getFileUploaderWidget() { 
        form.setEncoding(FormPanel.ENCODING_MULTIPART); 
        form.setMethod(FormPanel.METHOD_POST); 
        form.setAction(URL_UPLOAD_IMAGES);
       
 
        VerticalPanel holder = new VerticalPanel(); 
 
        fu.setName("upload"); 
        holder.add(fu); 
        holder.add(new Button("Enviar", new ClickHandler() { 
                public void onClick(ClickEvent event) { 
                       form.submit(); 
                } 
        })); 
        
        form.addSubmitHandler(new FormPanel.SubmitHandler() { 
                public void onSubmit(SubmitEvent event) { 
                        if ("".equalsIgnoreCase(fu.getFilename())) {
                                event.cancel(); // cancel the event 
                        } 
 
                } 
        }); 
 
        form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() { 
                public void onSubmitComplete(SubmitCompleteEvent event) {
                        imagen.setUrl("/youvote/file?id=" + parseString(event.getResults()));
                        
                } 
        }); 
        
        holder.add(imagen);
        form.add(holder); 
        return form; 
    } 

	
}
